HGetState does not return a valid handle state when you pass it an empty handle (one whose master pointer is NULL). Instead, it returns an error code, so before you call HGetState, be sure to check that the handle isn’t empty and execute an alternate code path if it is.
I was bitten by this because I was using HGetState to determine if a handle was to a resource, and the resource had been purged, so HGetState returned an error code instead of the handle flags, and I incorrectly decoded the return result and thought the handle wasn’t to a resource.
Eric Schlegel
From Inside Macintosh:
Memory, page 1-61 to 1-62:
If an error occurs during an attempt to get the state flags of the specified relocatable block, HGetState returns the low-order byte of the result code as its function result. For example, if the handle h points to a master pointer whose value is NIL, then the signed byutle returned by HGetState will contain the value -109.
Result codes:
noErr 0
nilHandleErr -109 NIL master pointer
memWZErr -111 Attempt to operate on a free block
An Old Bug, Turns Out to be “An Old Bug”
I think I found a bug in a Tip in the March 1995 issue of MacTech magazine. The Tip, entitled “Hot Tip for Hot Keys”, can be found on page 67. Allow me to quote a segment of code:
else
{
num = CountDITL(theDialog);
for(i=0; i<num; i++)
{
GetDItem(theDialog, i, &iType, &iHandle, &iRect);
//and so on ... the omitted code works wonderfully!
}
}
The problem is that the for loop is counting from 0 to Number-Of-DITL-Items minus 1. While the for loop is executed the correct number of times, it’s starting and ending one index too early. This off-by-one error is relatively common in C. Either the for loop should be:
for (i=1; i<=num; i++)
or the next line should read:
GetDItem(theDialog, i + 1, &iType, &iHandle, &iRect);
This error is a little hard to detect. Calling GetDItem with itemNo set to 0 doesn’t cause any harm. The only effect this bug has is the final entry in the DITL isn’t included in the search. This final item usually isn’t a push button, so the author didn’t notice the error in his own routine. Otherwise, this code works wonderfully; I use a repaired version all the time!
Mike Trent
A More General Context Sensitive Cursor
In the December issue of MacTech, a technique for making your application WindowShade-savvy was presented, which checked the current content region of the window to see if it was null. A more general method for setting the cursor, which works for WindowShade as well as handling the cases of the cursor outside of the window and when the cursor is in a floating window over the active window is: